package com.demo.starter.web;

import com.demo.starter.constant.SiteViews;
import com.demo.starter.domain.vo.ArticleCategoryVO;
import com.demo.starter.domain.vo.ArticleDetailVO;
import com.demo.starter.service.IArticleCategoryService;
import com.demo.starter.service.IArticleService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@Log4j2
public class ArticleController extends BaseController {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private IArticleCategoryService articleCategoryService;

    /**
     * 栏目列表
     * @return
     */
    @RequestMapping("/category")
    public ModelAndView category() {
        final ModelAndView view = new ModelAndView(SiteViews.CATEGORY);
        log.debug("PATH = /article/");
        final List<ArticleCategoryVO> categories = articleCategoryService.list();
        view.addObject("categories", categories);
        return view;
    }

    /**
     * 栏目详情
     * @param categoryId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("/category/{categoryId}")
    public ModelAndView categoryDetail(
            @PathVariable(name="categoryId") Long categoryId,
            @RequestParam(name="pageNum", defaultValue="1") Integer pageNo,
            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        final ModelAndView view = new ModelAndView(SiteViews.CATEGORY_DETAIL);
        log.debug("PATH = /article/");
        ArticleCategoryVO category = articleCategoryService.getById(categoryId);
        final List<ArticleDetailVO> articles = articleService.listByCategoryId(categoryId);
        final List<ArticleDetailVO> hotArticles = articleService.listHot(pageNo, pageSize);
        view.addObject("category", category);
        view.addObject("articles", articles);
        view.addObject("hotArticles", hotArticles);
        return view;
    }

    /**
     * 文章详情
     * @param id
     * @return
     */
    @RequestMapping(value = {"/article/{id}", "/article/{id}.html"})
    public ModelAndView articleDetail(@PathVariable(name="id") Long id) {
        final ModelAndView view = new ModelAndView(SiteViews.ARTICLE_DETAIL);
        log.debug("PATH = /article/{}", id);
        ArticleDetailVO article = articleService.getById(id);
        final List<ArticleDetailVO> hotArticles = articleService.listHot(1, 6);
        view.addObject("article", article);
        view.addObject("hotArticles", hotArticles);
        return view;
    }

}
